﻿using System;
using System.Net;
using System.ServiceModel.Web;
using System.Web;
using Restful.Net.Serialization;

namespace Restful.Net
{
    public class RestContext : IRestContext
    {
        private readonly HttpContextBase httpContext;

        public RestContext(HttpContext httpContext)
        {
            this.httpContext = new HttpContextWrapper(httpContext);
            CreateRequest();
            CreateResponse();
            current = this;
        }

        [ThreadStatic]
        private static IRestContext current;

        public static IRestContext Current
        {
            get
            {
                return current;
            }
            internal set
            {
                current = value;
            }
        }

        private void CreateResponse()
        {
            Response = new RestResponse(httpContext.Response);
        }

        private void CreateRequest()
        {
            if (httpContext.Request.HttpMethod == "POST" || httpContext.Request.HttpMethod == "PUT" || httpContext.Request.HttpMethod == "PATCH")
            {
                ISerializer serializer = RestRouter.Instance.Serializers.Find(s => s.Supports(httpContext.Request.ContentType));

                if (serializer == null)
                {
                    throw new WebFaultException<string>("Unknown content type", HttpStatusCode.UnsupportedMediaType);
                }

                Request = new RestRequest(httpContext.Request, serializer);
            }
            else
            {
                Request = new RestRequest(httpContext.Request, null);
            }

            CurrentUser = new AnonymousUser();
        }

        public IRequest Request
        {
            get;
            private set;
        }

        public IResponse Response
        {
            get;
            private set;
        }

        public IUser CurrentUser
        {
            get;
            set;
        }
    }
}
